﻿using System.Net.NetworkInformation;

namespace ECommon
{
    /// <summary>
    /// 端口工具类
    /// </summary>
    public static partial class PortTool
    {
        /// <summary>
        /// 检测本机端口是否可用
        /// </summary>
        /// <param name="port">本机端口</param>
        /// <returns>检测结果</returns>
        public static bool IsPortAvailable(int port)
        {
            IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
            TcpConnectionInformation[] connections = properties.GetActiveTcpConnections();

            foreach (TcpConnectionInformation connection in connections)
            {
                if (connection.LocalEndPoint.Port == port)
                {
                    // 端口已被占用
                    return false;
                }
            }
            // 端口未被占用
            return true;
        }
    }
}
